package org.dxy.domain.handler.workstation;

import com.google.common.eventbus.EventBus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dxy.domain.command.workstation.WorkstationOutCommand;
import org.dxy.domain.event.DomainEvent;
import org.dxy.domain.model.aggregate.Workstation;
import org.dxy.domain.handler.CommandHandler;
import org.dxy.domain.port.repository.IWorkstationRepository;
import org.dxy.types.common.CommandResult;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @description: 工位出站命令处理器
 * @author: dxy
 * @createTime: 2025/10/13
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WorkstationOutCommandHandler implements CommandHandler<WorkstationOutCommand, Long> {

    private final IWorkstationRepository workstationRepository;
    private final EventBus eventBus;
    @Transactional
    @Override
    public CommandResult<Long> handle(WorkstationOutCommand command) {
        try {
            log.info("开始处理工位出站命令: workstationId={}, serialNumber={}, qualityResult={}", 
                    command.workstationId(), command.serialNumber(), command.qualityResult());

            Workstation workstation = workstationRepository.findById(command.workstationId());

            // 4. 执行进站操作
            workstation.stationOut(command);

            // 5. 更新聚合
            workstationRepository.update(workstation);

            // 6. 获取并发布领域事件
            List<DomainEvent> events = workstation.getDomainEvents();
            for (DomainEvent event : events) {
                log.info("发布领域事件: {}", event.getClass().getSimpleName());
                eventBus.post(event);
            }

            // 7. 清除已发布的事件
            workstation.clearDomainEvents();

            log.info("工位出站命令处理完成, workstationId={}, serialNumber={}, qualityResult={}",
                    command.workstationId(), command.serialNumber(), command.qualityResult());
            return CommandResult.success(null, "工位出站成功");

        } catch (Exception e) {
            log.error("工位出站失败: workstationId={}, serialNumber={}, qualityResult={}", 
                    command.workstationId(), command.serialNumber(), command.qualityResult(), e);
            return CommandResult.fail(null, "工位出站失败: " + e.getMessage());
        }
    }
}